<!-- 科目 -->
<script setup lang='ts'>
import { reactive, onMounted, ref } from 'vue'
import { useCurrentInstance } from '@/common/utils/methods';
import { ResponseType } from '@/common/types/response';
import type { ElForm } from 'element-plus'
type FormInstance = InstanceType<typeof ElForm>
const { $axios, $confirm, $message, branchId, brandId, branchType } = useCurrentInstance();

interface subjectType {
  branchId: string
  brandId: string
  opsType: number
  title: string
  subjectId?: string
  [propName: string]: any
}

const data = reactive({
  subjectList: [],
  activeSubject: {} as subjectType,
  pageNo: 1,
  pageSize: 10,
  totalRowCount: 0,
  loading: false,
  showEditDialog: false,
})

const checkTitle = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入科目'))
  } else {
    if (value.replace(/\s/g, '') === '') {
      return callback(new Error('请输入有效字符'))
    } else {
      if (value.length >= 2 && value.length <= 10) {
        callback()
      } else {
        callback(new Error('科目长度2-10字'))
      }
    }
  }
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({ title: '', opsType: 1, subjectId: '' })
const rules = reactive({
  title: [{
    required: true,
    validator: checkTitle,
    trigger: 'blur'
  }]
})

const getSubjectList = () => {
  data.loading = true;
  $axios.post('/training.exam.api/subject/list', {
    branchId,
    brandId,
    pageNo: data.pageNo,
    pageSize: data.pageSize
  }).then((res: ResponseType) => {
    const { data: { list = [], totalRowCount = 0 }, code } = res;
    if (code === '200') {
      data.subjectList = list;
    } else {
      data.subjectList = [];
    }
    data.totalRowCount = Number(totalRowCount);
    data.loading = false;
  })
}

const sizeChange = (pageSize: number) => {
  data.pageSize = pageSize;
  data.pageNo = 1;
  getSubjectList();
}

const currentChange = (pageNo: number) => {
  data.pageNo = pageNo;
  getSubjectList();
}

const addSubject = () => {
  ruleForm.title = '';
  ruleForm.opsType = 1;
  data.showEditDialog = true;
}
const editSubject = (subject: subjectType) => {
  ruleForm.title = subject.title;
  ruleForm.opsType = 2;
  data.activeSubject = subject;
  data.showEditDialog = true;
}
const saveSubject = () => {
  let params = { branchId, brandId, ...ruleForm } as subjectType;
  if (params.opsType === 2) {
    params.subjectId = data.activeSubject.subjectId;
  }
  $axios.post('/training.exam.api/subject/create', params).then((res: ResponseType) => {
    if (res.code === '200') {
      data.pageNo = 1;
      getSubjectList();
      $message.success(`${ruleForm.opsType === 1 ? '新增' : '更新'}成功`);
    } else {
      $message.error('操作失败');
    }
  })
}

const deleteSubject = (subject: subjectType) => {
  $confirm(
    '<p>确定删除科目么？</p><p class="_tip _required">若该科目下有试题，则无法删除</p>',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      dangerouslyUseHTMLString: true,
      type: 'warning',
      canter: true
    }).then(() => {
      $axios.post('/training.exam.api/subject/enableOrDelete', {
        brandId,
        branchId,
        status: -1,
        subjecIds: [subject.subjectId]
      }).then((res: ResponseType) => {
        if (res.code === '200') {
          getSubjectList();
          $message.success('删除成功')
        } else {
          $message.error('删除失败')
        }
      })
    }).catch(() => {
      console.log('subject-delete-cancel');
    })
}

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  if (data.activeSubject.title === ruleForm.title) {
    data.showEditDialog = false;
    return;
  };
  formEl.validate((valid) => {
    if (valid) {
      if (ruleForm.opsType === 2) {
        $confirm(
          '<p>确定修改科目么？</p><p class="_tip _required">修改后使用该科目的试题将自动同步新的科目</p>',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            dangerouslyUseHTMLString: true,
            type: 'warning',
            canter: true
          }
        ).then(() => {
          saveSubject();
        }).catch(() => {
          console.log('subject-confirm-cancel')
        })
      } else {
        saveSubject();
      }
      data.showEditDialog = false;
    }
  })
}

const beforeClose = (done: Function) => {
  ruleFormRef?.value?.resetFields()
  done();
}

onMounted(() => {
  getSubjectList();
})
</script>

<template>
  <div>
    <div class="subject-list-btn">
      <el-button type="primary" icon="plus" @click="addSubject">添加科目</el-button>
    </div>
    <el-table :data="data.subjectList" border style="width: 100%" v-loading="data.loading">
      <el-table-column prop="title" label="科目" />
      <el-table-column fixed="right" align="center" label="操作" width="180">
        <template #default="scope">
          <el-button-group>
            <el-button
              @click="editSubject(scope.row)"
              :disabled="branchType === 2 && scope.row.ownerType === 1"
            >修改</el-button>
            <el-button
              @click="deleteSubject(scope.row)"
              :disabled="branchType === 2 && scope.row.ownerType === 1"
            >删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <div style="display:flex;justify-content: center;margin-top:20px">
      <el-pagination
        v-model:currentPage="data.pageNo"
        v-model:page-size="data.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.totalRowCount"
        @size-change="sizeChange"
        @current-change="currentChange"
      ></el-pagination>
    </div>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="data.showEditDialog" title="编辑" width="30%" :before-close="beforeClose">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
        <el-form-item label="科目" prop="title">
          <el-input v-model="ruleForm.title"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.subject-list-btn {
  text-align: right;
  margin-bottom: 10px;
}
</style>